//
//  MainBoradViewController.m
//  TestARC
//
//  Created by wuxiaoquan on 12-9-22.
//  Copyright (c) 2012年 wuxiaoquan. All rights reserved.
//
#import "BaseSearchViewController.h"

#import "MainBoradViewController.h"
#import "DrugSearchViewController.h"
#import "DiseaseViewController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "HelpViewController.h"
#import "UpdateViewController.h"
#import "AboutViewController.h"
#import "DrugDetailViewController.h"
#import "DiseaseDetailViewController.h"
#import "MyExtensions.h"
#import "JSON/SBJson.h"
#import "DiseaseSymtomViewController.h"
#import "DiseaseDrugViewController.h"
#import <MessageUI/MFMailComposeViewController.h> 
#import "BlueButton.h"
#import "FeedbackBoardViewController.h"


@interface MainBoradViewController ()

@end

@implementation MainBoradViewController
@synthesize mailPicker;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.rightBarButtonItem = nil;
    [self.navigationController setNavigationBarHidden:TRUE animated:YES];
    self.title = @"首页";
    self.searchBar.placeholder = @"请输入...";
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:TRUE animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:FALSE animated:YES];
}

-(IBAction)putChildController:(id)sender
{
    int index = [sender tag];
    BaseSearchViewController *myDrugController = nil;
    LoginViewController *myLoginController = nil;
    RegisterViewController *myRegisterController = nil;
    HelpViewController *myHelpController= nil;
    UpdateViewController *myUpdateController = nil;
    AboutViewController *myAboutController = nil;
    FeedbackBoardViewController *myFeedbackController = nil;
    
    
    switch (index) {
        case 1:
            //药品
            myDrugController = [[DrugSearchViewController alloc]initWithNibName:@"BaseSearchViewController" bundle:nil];
            [self.navigationController pushViewController:myDrugController animated:YES];
            break;
        
        case 2:
            //疾病
            myDrugController = [[DiseaseViewController alloc]initWithNibName:@"BaseSearchViewController" bundle:nil];
            [self.navigationController pushViewController:myDrugController animated:YES];
            break;
            
        case 3:
            //登陆
            myLoginController = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
            [self.navigationController pushViewController:myLoginController animated:YES];
            break;
            
        case 4:
            //注册
            myRegisterController = [[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil];
            [self.navigationController pushViewController:myRegisterController animated:YES];
            break;
            
        case 5:
            //帮助
            myHelpController = [[HelpViewController alloc]initWithNibName:@"HelpViewController" bundle:nil];
            [self.navigationController pushViewController:myHelpController animated:YES];
            break;
            
        case 6:
            //帮助
            myUpdateController = [[UpdateViewController alloc]initWithNibName:@"UpdateViewController" bundle:nil];
            [self.navigationController pushViewController:myUpdateController animated:YES];
            break;
            
        case 7:
            //设置反馈邮件
            /*
            self.mailPicker = nil;
            self.mailPicker = [[MFMailComposeViewController alloc] init];
            self.mailPicker.mailComposeDelegate = self;
            [self.mailPicker setSubject:@"反馈给药侠的问题"];
            [self.mailPicker setToRecipients:[NSArray arrayWithObjects:@"mobile@yaoxia.com", nil]];
            [self.mailPicker setMessageBody:@"请填入问题：" isHTML:NO];
            
            [self.navigationController presentModalViewController:self.mailPicker animated:YES];
             */
            
            //反馈
            myFeedbackController = [[FeedbackBoardViewController alloc]initWithNibName:@"FeedbackBoardViewController" bundle:nil];
            [self.navigationController pushViewController:myFeedbackController animated:YES];
            break;
            
        case 8:
            //帮助
            myAboutController = [[AboutViewController alloc]initWithNibName:@"AboutViewController" bundle:nil];
            [self.navigationController pushViewController:myAboutController animated:YES];
            break;
            
        default:
            break;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil; 
    self.mailPicker = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//---------------------一直隐藏topBar-----------------
-(void)endSearch
{
    [super endSearch];
    [self.navigationController setNavigationBarHidden:TRUE animated:YES];
}
// ------------------ 搜索相关---------------------------
-(void)loadSeggestionData:(NSString *)queryText
{
    [self.seggestionArray removeAllObjects];
    FMResultSet *rs =[self.dbHelper searchBothSeggestion:queryText];
    //NSLog(@"rs.query=%@",rs.query);
    while ([rs next]) {
        [self.seggestionArray addObject:[rs resultDictionary]];
    }
    
}

-(void)setCellImage:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    NSDictionary *detail = [self.seggestionArray objectAtIndex:row];
    NSString *commonName = [detail objectForKey:@"CommonName"];
    if ([commonName isEqualToString:@"use4disease"]) {
        //疾病
        cell.imageView.image = [UIImage imageNamed:@"table_disease_logo_23.png"];
    }
    else
    {
        //药品
        cell.imageView.image = [UIImage imageNamed:@"table_drug_logo_23.png"];
    }
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //填装详细视图的内容。
    int row = [indexPath row];
    NSDictionary *detail = [self.seggestionArray objectAtIndex:row];
    NSString *commonName = [detail objectForKey:@"CommonName"];
    if ([commonName isEqualToString:@"use4disease"]) {
        //疾病
        [self loadDiseaseDetailData:detail];
    }
    else
    {
        //药品
        DrugDetailViewController * detailController = [[DrugDetailViewController alloc]initWithNibName:@"DrugDetailViewController" bundle:nil];
        
        detail = [self.seggestionArray objectAtIndex:row];
        
        detailController.name =       [detail objectForKey:@"name"];
        detailController.brandName =  [detail objectForKey:@"BrandName"];
        detailController.commonName = [detail objectForKey:@"CommonName"];
        detailController.queryId =    [detail objectForKey:@"queryid"];
        
        [self.navigationController pushViewController:detailController animated:YES];
        
    } 
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//-----------显示疾病详细的代码---------
- (void) loadDiseaseDetailData:(NSDictionary *)detail
{
    //NSLog(@"disease=%@",detail); 
    NSString *queryid = [detail objectForKey:@"queryid"];
    NSString *flag = @"B90";
    int timestamp = (int)[[NSDate date]timeIntervalSince1970];
    NSString * checksum = [[NSString stringWithFormat:@"%d%@%d%@%dyaoxia",timestamp,flag,timestamp,queryid,timestamp]md5];
    NSString *URL_DETAIL = [NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet?style=ae062a0f29297c33f8ab85b1d4b7741f&flag=%@&key=%@&timestamp=%d&checksum=%@",flag,queryid,timestamp,checksum];
    NSURL *url = [NSURL URLWithString:URL_DETAIL];
    request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        // Use when fetching text data
        NSString *responseString = [request responseString];
        
        //NSLog(@"responseString = %@",responseString);
        id json = [responseString JSONValue];
        //NSLog(@"meg = %@",[json objectForKey:@"drugInfo"]);
        if ([[json objectForKey:@"code"]intValue] == 500) {
            NSLog(@"%@",[json objectForKey:@"message"]);
            return ;
        }
        
        [self showDiseaseDetailView:json diseaseName:[detail objectForKey:@"name"]];
        
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request setFailedBlock:^{
        NSError *error = [request error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request startAsynchronous];
    
    
    
}

- (void) showDiseaseDetailView:(NSDictionary *)json diseaseName:(NSString *)name
{
    //设置标签栏
    UITabBarController *tabController = [[UITabBarController alloc] init];
    tabController.title = name;
    BlueButton *blueButton = [[BlueButton alloc] init];
    [blueButton addTarget:self action:@selector(backToMain) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *button = [[UIBarButtonItem alloc]
                               initWithCustomView:blueButton];
    tabController.navigationItem.rightBarButtonItem = button;
//    tabController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"药" style:UIBarButtonItemStylePlain target:self action:@selector(backToMain)];
    //tabController.tabBar.frame = CGRectMake(0, 64+50, 320, 70);
    //设置每个标签
    DiseaseDetailViewController *viewController1 = [[DiseaseDetailViewController alloc] initWithNibName:@"DiseaseDetailViewController" bundle:nil];
    UITabBarItem *tab1 = [[UITabBarItem alloc] initWithTitle:@"疾病简介"
                                                       image:[UIImage imageNamed:@"disease_detail_pref.png"]
                                                         tag:1];
    [viewController1 setTabBarItem:tab1];
    viewController1.url = [json objectForKey:@"briefUrl"];
    //[viewController1.view setBackgroundColor:[UIColor redColor]];
    
    
    DiseaseSymtomViewController *viewController2 = [[DiseaseSymtomViewController alloc] initWithNibName:@"DiseaseSymtomViewController" bundle:nil];
    UITabBarItem *tab2 = [[UITabBarItem alloc] initWithTitle:@"症状"
                                                       image:[UIImage imageNamed:@"disease_detail_sym.png"]
                                                         tag:2];
    [viewController2 setTabBarItem:tab2];
    viewController2.symptomArray = [json objectForKey:@"symptomArray"];
    //[viewController2.view setBackgroundColor:[UIColor greenColor]];
    
    DiseaseDrugViewController *viewController3 = [[DiseaseDrugViewController alloc] initWithNibName:@"DiseaseDrugViewController" bundle:nil];
    UITabBarItem *tab3 = [[UITabBarItem alloc] initWithTitle:@"治疗药物"
                                                       image:[UIImage imageNamed:@"disease_detail_drug.png"]
                                                         tag:3];
    [viewController3 setTabBarItem:tab3];
    //[viewController3.view setBackgroundColor:[UIColor blueColor]];
    viewController3.drugArray = [json objectForKey:@"drugArray"];
    
    
    tabController.viewControllers = [NSArray arrayWithObjects:viewController1,
                                     viewController2,
                                     viewController3,
                                     nil];
    
    [self.navigationController pushViewController:tabController animated:YES];
}

//---------------邮件委托--------------
- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error {
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail send canceled...");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved...");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent...");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail send errored: %@...", [error localizedDescription]);
            break;
        default:
            break;
    }
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

@end
